<script lang="tsx" setup>
import { computed, reactive, ref, watch } from 'vue';
import { type FormRules, NAvatar, NText } from 'naive-ui';
import type { DeptVO, PostVO } from '@/service/types/system';
import { addPost, editPost, getPost } from '@/service/api/system/post';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import type { DictDataOption } from '@/typings/global';
type Model = Pick<PostVO, 'deptId' | 'status' | 'postCode' | 'postId' | 'postSort' | 'postName' | 'postCategory'>;
interface Props {
  operateType: NaiveUI.TableOperateType;
  currentId?: string | number | null | unknown;
  depts: DeptVO[];
  sysNormalDisable: DictDataOption[];
}
const loading = ref(false);
interface Emits {
  (e: 'submitted'): void;
}
const show = ref<boolean>(false);
const props = defineProps<Props>();
const emit = defineEmits<Emits>();
defineOptions({
  name: 'PostForm'
});
const { formRef, validate, restoreValidation } = useNaiveForm();
const { createRequiredRule } = useFormRules();
const rules: FormRules = {
  postSort: createRequiredRule('显示顺序不能为空'),
  deptId: createRequiredRule('所属部门不能为空'),
  postName: {
    required: true,
    min: 1,
    max: 50,
    message: '岗位称长度必须介于 1 和 50 之间',
    trigger: 'blur'
  },
  deptCategory: {
    required: false,
    min: 1,
    max: 100,
    message: '部门类别编码称长度必须介于 1 和 100 之间',
    trigger: 'change'
  },
  postCode: {
    required: true,
    min: 1,
    max: 64,
    message: '岗位编码称长度必须介于 1 和 64 之间',
    trigger: 'blur'
  }
};

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增岗位',
    edit: '修改岗位'
  };
  return titles[props.operateType];
});
const visible = defineModel<boolean>('visible', {
  default: false
});
const currentModelData = ref<PostVO>();
const model: Model = reactive(createDefaultModel());
function createDefaultModel(): Model {
  return {
    postId: '',
    status: '0',
    deptId: '',
    postSort: 0,
    postCategory: '',
    postName: '',
    postCode: ''
  };
}
const getPostById = async (id: number) => {
  show.value = true;
  const { error, data } = await getPost(id);
  if (!error) {
    currentModelData.value = data?.data;
  }
  show.value = false;
};

async function handleInitModel() {
  Object.assign(model, createDefaultModel());
  if (props.operateType === 'edit' && props.currentId) {
    await getPostById(props.currentId as number);
    Object.assign(model, currentModelData.value);
  }
}
watch(visible, () => {
  if (visible.value) {
    // handleGetUserList();
    handleInitModel();
    restoreValidation();
  }
});

const closeModal = () => {
  visible.value = false;
};
const submitAddPost = async (params: PostVO) => {
  const { error, data } = await addPost(params);
  loading.value = false;
  if (!error) {
    (window as any).$message?.success(data?.msg);
    closeModal();
    emit('submitted');
  }
};
const submitEditPost = async (params: PostVO) => {
  const { error, data } = await editPost(params);
  loading.value = false;
  if (!error) {
    (window as any).$message?.success(data?.msg);
    closeModal();
    emit('submitted');
  }
};
async function handleSubmit() {
  await validate();
  loading.value = true;
  const { ...params } = model;
  if (!props.currentId) {
    await submitAddPost(params as PostVO);
  } else {
    await submitEditPost({ ...params, postId: props.currentId } as PostVO);
  }
}
</script>

<template>
  <NModal v-model:show="visible" :title="title" preset="card" class="w-740px">
    <NSpin :show="show">
      <NForm ref="formRef" :model="model" :rules="rules">
        <NGrid x-gap="12" responsive="screen" item-responsive>
          <NFormItemGi span="24 s:12 m:12" label="所属部门" path="deptId">
            <NTreeSelect
              v-model:value="model.deptId"
              placeholder="请选择所属部门"
              label-field="label"
              filterable
              key-field="id"
              :options="props.depts"
            />
          </NFormItemGi>
          <NFormItemGi span="24 s:12 m:12" label="岗位名称" path="postName">
            <NInput v-model:value="model.postName" placeholder="请输入岗位名称" />
          </NFormItemGi>
          <NFormItemGi span="24 s:12 m:12" label="岗位编码" path="postCode">
            <NInput v-model:value="model.postCode" placeholder="请输入岗位编码" />
          </NFormItemGi>
          <NFormItemGi span="24 s:12 m:12" label="类别编码" path="postCategory">
            <NInput v-model:value="model.postCategory" placeholder="请输入类别编码" />
          </NFormItemGi>
          <NFormItemGi span="24 s:12 m:12" label="岗位排序" path="postSort">
            <NInputNumber
              v-model:value="model.postSort"
              :min="0"
              :max="9999"
              class="w-100%"
              clearable
              placeholder="排序"
            />
          </NFormItemGi>
          <NFormItemGi span="24 s:12 m:12" label="状态" path="status">
            <NRadioGroup v-model:value="model.status">
              <NRadioButton v-for="(item, index) in props.sysNormalDisable" :key="index" :value="item.value">
                {{ item?.label }}
              </NRadioButton>
            </NRadioGroup>
          </NFormItemGi>
        </NGrid>
      </NForm>
    </NSpin>

    <template #footer>
      <NSpace justify="end">
        <NButton @click="closeModal">取消</NButton>
        <NButton type="primary" :loading="loading" @click="handleSubmit">提交</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style lang="scss" scoped></style>
